package cn.jtool.dig.server.service.impl;

import cn.jtool.dig.server.dao.repository.LogConnectRepository;
import cn.jtool.dig.server.domain.response.LogConnectListResponse;
import cn.jtool.dig.server.domain.response.LogTrafficListResponse;
import cn.jtool.dig.server.service.DataReportService;
import cn.jtool.knife.core.result.PageResultEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.metamodel.Metamodel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class DataReportServiceImpl implements DataReportService {

    @Resource
    private EntityManager entityManager;
    @Resource
    private LogConnectRepository logConnectRepository;

    @Override
    public PageResultEntity<LogConnectListResponse> connect(int page, int limit) {
        PageHelper.startPage(page, limit);
        List<LogConnectListResponse> list = this.entityManager.createNativeQuery("select " +
                "LOG_CONNECT.ID as id, " +
                "LOG_CONNECT.CONNECT_TIME as connectTime, " +
                "LOG_CONNECT.DIS_CONNECT_TIME as disConnectTime," +
                "LOG_CONNECT.SOURCE_SERVER as sourceServer, " +
                "LOG_CONNECT.REC_BYTES as recBytes, " +
                "LOG_CONNECT.SEND_BYTES as sendBytes," +
                "LICENSE.LICENSE_NAME as licenseName,  " +
                "PORT_MAPPING.PORT_MAPPING_NAME as portMappingName " +
                "from LOG_CONNECT " +
                "left join LICENSE on LOG_CONNECT.LICENSE_ID=LICENSE.ID " +
                "left join PORT_MAPPING on LOG_CONNECT.PORT_MAPPING_ID=PORT_MAPPING.ID ORDER BY LOG_CONNECT.CONNECT_TIME DESC", LogConnectListResponse.class).getResultList();
        PageInfo<LogConnectListResponse> pageInfo = new PageInfo<>(list);
        return PageResultEntity.of(pageInfo);
    }

    @Override
    public PageResultEntity<LogTrafficListResponse> traffic(int page, int limit) {
        PageHelper.startPage(page, limit);
        List<LogTrafficListResponse> resultList = this.entityManager.createNativeQuery("SELECT " +
                "LOG_TRAFFIC.ID as id, " +
                "PORT_MAPPING.PORT_MAPPING_NAME as portMappingName, " +
                "LOG_TRAFFIC.REC_BYTES as recBytes, " +
                "LOG_TRAFFIC.SEND_BYTES as sendBytes, " +
                "LOG_TRAFFIC.TIME_TAG as timeTag " +
                "from LOG_TRAFFIC " +
                "left join PORT_MAPPING on LOG_TRAFFIC.PORT_MAPPING_ID = PORT_MAPPING.ID", LogTrafficListResponse.class).getResultList();
        PageInfo<LogTrafficListResponse> pageInfo = new PageInfo<>(resultList);
        return PageResultEntity.of(pageInfo);
    }
}
